package com.googlecode.monitoring.webpages.jobs;

import com.googlecode.monitoring.config.SpringApplicationContext;
import com.googlecode.monitoring.dao.AgentConfigurationDao;
import com.googlecode.monitoring.dao.AgentStatusDao;
import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.StateName;
import com.googlecode.monitoring.service.DefaultEmailService;
import com.googlecode.monitoring.service.MonitoringService;
import com.googlecode.monitoring.webpages.model.WebPageItemToCheck;
import org.apache.log4j.Logger;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

/**
 * Author: Sergiy Doroshenko
 * Date: Aug 25, 2010
 * Time: 11:52:32 AM
 */
public class WebPagePingJob extends QuartzJobBean{
    Logger log = Logger.getLogger(WebPagePingJob.class);
    private MonitoringService monitoringService;
    private DefaultEmailService emailService;
    private AgentStatusDao agentStatusDao;
    private AgentConfigurationDao agentConfigurationDao;

    public WebPagePingJob() {
        monitoringService = SpringApplicationContext.getBean(MonitoringService.class);
        emailService = SpringApplicationContext.getBean(DefaultEmailService.class);
        agentStatusDao = SpringApplicationContext.getBean(AgentStatusDao.class);
        agentConfigurationDao =  SpringApplicationContext.getBean(AgentConfigurationDao.class);
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		WebPageItemToCheck webPageItem = (WebPageItemToCheck) dataMap.get("item");
		log.debug(webPageItem);

        boolean testfailed = monitoringService.checkIsItemOutdated(webPageItem);
        if (testfailed) {
            ItemToCheck wsItemFromReport = agentStatusDao.getItemFromCheckReport(webPageItem);
            if (wsItemFromReport == null || !wsItemFromReport.getCurrentStateName().equals(StateName.EMAIL_SENT)) {
                emailService.sendAlertEmail(webPageItem, agentConfigurationDao.getCommonResponsiblePersons());
                log.warn("The " + webPageItem.getName() + " service is DOWN, an alert email is sent");
            }
            webPageItem.switchState(com.googlecode.monitoring.model.StateName.EMAIL_SENT);
        }
        agentStatusDao.saveItemToCheckReport(webPageItem);
    }
}
